package utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName BaseDBManager
 * @Deacription 数据库管理基础类
 * @Author wushumin
 * @Date 2020/7/13 9:59
 * @Version 1.0
 **/
@Slf4j
public class BaseDBManager {


    public static void connectionClose(Connection conn) {
        try {
            conn.close();
        } catch (SQLException e) {
            log.error("======>sensors connection close error:{}", e);//错误异常完整写入日志文件
        }
    }


    public static void releaseResource(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            log.error("======>releaseResource impala jdbc rerror:{}", e);
        }
    }

    public static void fillParams(PreparedStatement pstmt, List<Object> param) throws SQLException {
        for (int i = 1; i <= param.size(); i++) {
            Object obj = param.get(i - 1);
            if (obj instanceof Boolean) {
                pstmt.setBoolean(i, (boolean) obj);
            } else if (obj instanceof Byte) {
                pstmt.setByte(i, (byte) obj);
            } else if (obj instanceof Short) {
                pstmt.setShort(i, (short) obj);
            } else if (obj instanceof Integer) {
                pstmt.setInt(i, (int) obj);
            } else if (obj instanceof Long) {
                pstmt.setLong(i, (long) obj);
            } else if (obj instanceof Float) {
                pstmt.setFloat(i, (float) obj);
            } else if (obj instanceof Double) {
                pstmt.setDouble(i, (double) obj);
            } else if (obj instanceof String) {
                pstmt.setString(i, String.valueOf(obj));
            }
        }
    }
}
